﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Text;
using Rison.Web.Common;
using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Entity.XT;
using Rison.BusinessFacade.Facade.XT;
using Rison.BusinessFacade.Helper;
using Microsoft.Fareast.MCS.SSO.Client;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Rison.DataAccess.Data.ZJCP;

namespace Rison.Web
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
                CurrentLoginedUser.ClearUserSession();

            if (!Request.IsAuthenticated)
            {

            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (StringHelper.IsNullOrEmpty(this.txtUserId.Text))
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('请输入用户名！');</script>");
            //this.labMsg.Text = "请输入用户名！";
            else if (!StringHelper.IsMergeByNumberAndChar(txtUserId.Text.Trim(), "_"))
                //this.labMsg.Text = "用户名输入非法！";
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('用户名输入非法！');</script>");
            else if (StringHelper.IsNullOrEmpty(this.txtPwd.Text))
                //this.labMsg.Text = "请输入密码！";
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('请输入密码！');</script>");
            else if("admin".Equals(this.txtUserId.Text))
            {
                if ("cnxmAdmin".Equals(this.txtPwd.Text))
                {
                    CurrentLoginedUser.SetCurrentUser(txtUserId.Text.Trim(), txtUserId.Text.Trim(), this.txtPwd.Text.Trim());
                    Response.Redirect("ZJCP/ExpertDepartSet.aspx");
                    return;
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('对不起，用户名或密码错误！');</script>");
                    return;
                }
            }
            else if (expertLogin())
            {
                CurrentLoginedUser.SetCurrentUser(findExId(txtUserId.Text.Trim()), txtUserId.Text.Trim(), this.txtPwd.Text.Trim());
                Response.Redirect(String.Format("ZJCP/ExpertGrade.aspx?timestamp={0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")));
                return;
            } 
            else
            {
                //内部用户
                object result = InvokeWebService();
                //CurrentLoginedUser.SetCurrentUserId(txtUserId.Text.Trim(), this.txtPwd.Text, "1");


                if (result.ToString().ToLower() == "false")
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('对不起，用户名或密码错误！');</script>");
                }
                else if (result.ToString().ToLower() == "true")
                {
                    string username = txtUserId.Text.Trim();
                    CurrentLoginedUser.SetCurrentUser(username, username, this.txtPwd.Text.Trim());
                    string obj = GetDepartId(this.txtUserId.Text).ToString();
                    Regex r1 = new Regex(@"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}");
                    if (r1.IsMatch(obj))
                    {
                        int io = judgeIfExist(obj);
                        if (io > 0)
                        {
                            Response.Redirect("ZP/SelfExaminationView.aspx?DepartID=" + obj);
                            return;
                        }

                    }
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('所在部门不需要测评！');</script>");

                    //Response.Redirect("admin/DepartmentList.aspx");
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + result + "');</script>");
                }
            }


            //外部用户           

            //if (string.IsNullOrEmpty(CurrentLoginedUser.UserId))
            //    this.labMsg.Text = "对不起，用户名或密码错误！";
            //else if (!txtPwd.Text.Equals(CurrentLoginedUser.Password))
            //    this.labMsg.Text = "对不起，密码错误！";//区分大小写
            //else
            //    Response.Redirect("AdminView.aspx");


        }

        private object InvokeWebService()
        {
            string url = "http://authcenter.cn.gov/WebService/UserService.asmx";
            string method = "ValidateUser";
            //string url = "http://dept.changning.sh.cn/JFB.Gmail.AdminWeb/Mail/WebServices/SMS.asmx";
            //string method = "SendMessage";
            string[] args = new string[2];
            args[0] = this.txtUserId.Text;
            args[1] = this.txtPwd.Text;
            object result = DynamicWebServices.InvokeWebService(url, method, args);

            //result = "true"; //for test
            return result;
        }
        private object GetDepartId(string username)
        {
            string strCon = ConfigurationSettings.AppSettings["connectionStringW"];
            string strsql = String.Format("select MainDepartmentID from [user] t,[userLogin] t2 where t.id=t2.id and t2.loginName='{0}'", username);
            SqlConnection myConn = new SqlConnection(strCon);
            if (myConn.State.Equals(ConnectionState.Closed))
            {
                myConn.Open();
            }
            SqlDataAdapter da = new SqlDataAdapter(strsql, strCon);
            DataSet ds = new DataSet();
            da.Fill(ds);
            myConn.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0][0];
            }
            return "error";
        }
        private int judgeIfExist(string departid)
        {
            string strsql = String.Format("select count(1) from [Department] t where t.departid='{0}'", departid);
            DataSet ds = DbAccess.executeQuery(strsql);
            return (int)(ds.Tables[0].Rows[0][0]);
        }
        private Boolean expertLogin()
        {
            string userName = this.txtUserId.Text;
            string password = this.txtPwd.Text;
            string strsql = String.Format("select count(1) from Expert t where t.ex_user_name='{0}' and t.ex_user_password='{1}'", userName,password);
            DataSet ds = DbAccess.executeQuery(strsql);
            return (int)(ds.Tables[0].Rows[0][0]) > 0;
        }
        private string findExId(string userName)
        {
            string sql = String.Format("select ex_id from Expert t where t.ex_user_name='{0}'", userName);
            DataSet ds = DbAccess.executeQuery(sql);
            return ds.Tables[0].Rows[0][0].ToString();
        }
    }
}
